<?php
  header("Content-Type: text/plain; charset=UTF-8");
  $max = 20;
  // get input
  $name = htmlspecialchars(strip_tags(substr(@$_REQUEST['name'],0,20))); 
  $name = str_replace("\n"," ",$name);
  $name = str_replace("\r"," ",$name);
  $name = str_replace("\t"," ",$name);
  $message = htmlspecialchars(strip_tags(substr(@$_REQUEST['message'],0,1200)));
  $message = str_replace("\n"," ",$message);
  $message = str_replace("\r"," ",$message);
  $message = str_replace("\t"," ",$message);
  // load previous messages
  $f = file_get_contents("chat.txt");
  // limit total length of chat
  $f = explode("\n",$f,$max+1);
  //echo count($f)."\n\n";
  while (count($f) > $max)
    array_pop($f);
  //for ($i=0; $i<count($f); $i++) 
  //  echo "i=$i ".$f[$i]."-----\n\n";
  $z = implode("\n",$f);
  $s = '';
  // undefined name
  if ( (!empty($name))&&(!empty($message)) ) {  
    //echo "name=$name, message=$message";
    // insert new message
    $s = "<div class=\"post\"><span class=\"name\">".$name."</span><span class=\"message\">".$message."</span></div>\n";  
    $z = $s.$z;
    // write file
    file_put_contents("chat.txt",$z);
  }  
  echo $z;
?>